const {ElMessage,ElMessageBox} = ElementPlus;
const request = axios.create({
    baseURL:env.baseURL,
    timeout: 50000
});
request.interceptors.request.use(
    config => {
        // const token = localStorage.getItem('token'); // 假设token存储在localStorage中
        // if (token) {
        //     config.headers.Authorization = `Bearer ${token}`;
        // }
        return config;
    },
    error => {
        return Promise.reject(error);
    });

// 响应拦截器
request.interceptors.response.use(response => {
        let {status,message} = response;
        if(status!==200){
            showError(message)
        }else if(response.data.code===401){
            window.location.href = '/login'
        }
        return response;
    },
    error => {
        showError(error.message)
        return Promise.reject(error);
    });
function showError(msg){
    ElMessage({
        showClose: true,
        message: msg,
        type: 'error',
    })
}

//--------------公共方法---------------------

function response(res,context){
    const success = res.data.code==200;
    if(typeof context != 'boolean' || context){
        if(success){
            ElMessage.success(res.data.msg)
        }else {
            ElMessage.error(res.data.msg)
        }
    }
    if(context&&context.emit) context.emit('close',success)
    return success;
}

function beforeEdit(rows,callback){
    if (rows.value.length === 0||rows.value.length > 1) {
        ElMessage.error("请选择一条要修改的数据");
        return;
    }
    callback();
}

function beforeRemove(rows,callback){
    if (rows.value.length === 0) {
        ElMessage.error("请选择要删除的数据");
        return;
    }
    ElMessageBox.confirm("确定要删除选中的数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        callback();
    })
}